<template>
  <div class="guide-detail-page" v-loading="loading">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-5">
        <div class="flex flex-col space-y-3">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="text-sm">
            <el-breadcrumb-item :to="{ name: 'TravelGuides' }"
              >寻找攻略</el-breadcrumb-item
            >
            <el-breadcrumb-item>{{ guideDetail.title }}</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 标题和操作按钮 -->
          <div class="flex items-center justify-between">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white line-clamp-1 flex-1 mr-4"
            >
              {{ guideDetail.title }}
            </h1>
            <div class="flex items-center gap-3">
              <el-button-group>
                <el-button
                  type="primary"
                  plain
                  :icon="Share"
                  @click="handleShare"
                  >分享</el-button
                >
                <el-button
                  :type="guideDetail.isFavorited ? 'primary' : 'default'"
                  plain
                  :icon="Star"
                  @click="handleFavorite"
                >
                  {{ guideDetail.isFavorited ? "已收藏" : "收藏" }}
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-6">
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 攻略内容 -->
          <div
            class="guide-content bg-white dark:bg-gray-800 rounded-lg shadow-sm"
          >
            <!-- 基本信息 -->
            <div class="border-b border-gray-100 dark:border-gray-700 p-5">
              <div class="flex items-center gap-4 mb-3">
                <el-tag
                  :type="
                    guideDetail.type === 'official' ? 'success' : 'warning'
                  "
                  size="small"
                  effect="light"
                >
                  {{
                    guideDetail.type === "official" ? "官方攻略" : "用户分享"
                  }}
                </el-tag>
                <div
                  class="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><View /></el-icon>
                    {{ formatNumber(guideDetail.views) }}浏览
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Star /></el-icon>
                    {{ formatNumber(guideDetail.likes) }}点赞
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Timer /></el-icon>
                    {{ formatTime(guideDetail.date) }}
                  </span>
                </div>
              </div>
              <div
                class="flex items-center cursor-pointer"
                @click="$router.push(`/user/profile/${guideDetail.author?.id}`)"
                v-if="guideDetail.author"
              >
                <el-avatar
                  :size="48"
                  :src="guideDetail.author.avatar"
                  class="mr-3"
                />
                <div>
                  <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                    {{ guideDetail.author.name }}
                  </h3>
                  <p class="text-sm text-gray-500 dark:text-gray-400">
                    {{ formatTime(guideDetail.date) }}
                  </p>
                </div>
              </div>
            </div>

            <!-- 封面图 -->
            <div class="p-5" v-if="guideDetail.cover">
              <el-image
                :src="guideDetail.cover"
                class="w-full rounded-lg max-h-[400px] object-cover"
                fit="cover"
              >
                <template #error>
                  <div class="w-full rounded-lg h-[300px] flex items-center justify-center bg-gray-200 dark:bg-gray-600">
                    <el-icon :size="32" class="text-gray-400 dark:text-gray-500"><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>

            <!-- 攻略简介 -->
            <div class="px-5 pb-5">
              <div class="bg-primary-50 dark:bg-primary-900/20 rounded-lg p-4">
                <p
                  class="text-gray-600 dark:text-gray-300 text-sm leading-relaxed"
                >
                  {{ guideDetail.description }}
                </p>
              </div>
            </div>

            <!-- 行程安排 -->
            <div class="p-5 border-t border-gray-100 dark:border-gray-700" v-if="guideDetail.itinerary && guideDetail.itinerary.length">
              <h2 class="text-lg font-bold text-gray-900 dark:text-white mb-5">
                行程安排
              </h2>
              <el-timeline>
                <el-timeline-item
                  v-for="(day, index) in guideDetail.itinerary"
                  :key="index"
                  :timestamp="'第' + (index + 1) + '天'"
                  placement="top"
                >
                  <div class="timeline-content">
                    <h3 class="text-base font-medium mb-3">{{ day.title }}</h3>
                    <div class="space-y-4">
                      <div
                        v-for="(spot, spotIndex) in day.spots"
                        :key="spotIndex"
                        class="spot-item bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
                      >
                        <div class="flex items-center justify-between mb-2">
                          <h4 class="text-base font-medium">{{ spot.name }}</h4>
                          <span class="text-sm text-gray-500">{{
                            spot.time
                          }}</span>
                        </div>
                        <p
                          class="text-sm text-gray-600 dark:text-gray-400 mb-3 leading-relaxed"
                        >
                          {{ spot.description }}
                        </p>
                        <div class="grid grid-cols-2 gap-3">
                          <div
                            v-for="(image, imageIndex) in spot.images"
                            :key="imageIndex"
                            class="relative aspect-[4/3]"
                          >
                            <el-image
                              :src="image"
                              class="w-full h-full object-cover rounded-lg"
                              :preview-src-list="spot.images"
                            />
                          </div>
                        </div>
                        <div class="mt-3 space-y-2 text-xs">
                          <div v-if="spot.tips" class="flex items-start">
                            <el-icon class="mr-2 mt-0.5 text-gray-400"
                              ><InfoFilled
                            /></el-icon>
                            <span class="text-gray-600 dark:text-gray-400">{{
                              spot.tips
                            }}</span>
                          </div>
                          <div
                            v-if="spot.transportation"
                            class="flex items-start"
                          >
                            <el-icon class="mr-2 mt-0.5 text-gray-400"
                              ><Van
                            /></el-icon>
                            <span class="text-gray-600 dark:text-gray-400">{{
                              spot.transportation
                            }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>

            <!-- 美食推荐 -->
            <div class="p-5 border-t border-gray-100 dark:border-gray-700" v-if="guideDetail.foods && guideDetail.foods.length">
              <h2 class="text-lg font-bold text-gray-900 dark:text-white mb-5">
                美食推荐
              </h2>
              <div class="grid grid-cols-2 gap-4">
                <div
                  v-for="food in guideDetail.foods"
                  :key="food.id"
                  class="food-card bg-gray-50 dark:bg-gray-700 rounded-lg overflow-hidden"
                >
                  <el-image
                    :src="food.image"
                    class="w-full aspect-[16/9] object-cover"
                  >
                    <template #error>
                      <div class="aspect-[16/9] flex items-center justify-center bg-gray-200 dark:bg-gray-600">
                        <el-icon :size="24" class="text-gray-400 dark:text-gray-500"><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div class="p-3">
                    <h3
                      class="text-base font-medium text-gray-900 dark:text-white mb-2"
                    >
                      {{ food.name }}
                    </h3>
                    <p
                      class="text-xs text-gray-600 dark:text-gray-400 mb-2 line-clamp-2"
                    >
                      {{ food.description }}
                    </p>
                    <div class="text-xs text-gray-500 dark:text-gray-400">
                      <div class="flex items-center mb-1">
                        <el-icon class="mr-1"><Location /></el-icon>
                        {{ food.location }}
                      </div>
                      <div class="flex items-center">
                        <el-icon class="mr-1"><Wallet /></el-icon>
                        人均 ¥{{ food.price }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 注意事项 -->
            <div class="p-5 border-t border-gray-100 dark:border-gray-700" v-if="guideDetail.notes && guideDetail.notes.length">
              <h2 class="text-lg font-bold text-gray-900 dark:text-white mb-5">
                注意事项
              </h2>
              <div class="grid grid-cols-2 gap-4">
                <div
                  v-for="(note, index) in guideDetail.notes"
                  :key="index"
                  class="note-card bg-gray-50 dark:bg-gray-700 rounded-lg p-3"
                >
                  <h4 class="text-base font-medium mb-2">{{ note.title }}</h4>
                  <p class="text-sm text-gray-600 dark:text-gray-400">
                    {{ note.content }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-72 flex-shrink-0">
          <!-- 相关景点 -->
          <div
            class="related-spots bg-white dark:bg-gray-800 rounded-lg shadow-sm p-5 mb-5"
            v-if="guideDetail.relatedSpots && guideDetail.relatedSpots.length"
          >
            <h3
              class="text-base font-medium text-gray-900 dark:text-white mb-4"
            >
              相关景点
            </h3>
            <div class="space-y-4">
              <div
                v-for="spot in guideDetail.relatedSpots"
                :key="spot.id"
                class="spot-item group cursor-pointer"
                @click="$router.push('/spots/' + spot.id)"
              >
                <div class="relative rounded-lg overflow-hidden mb-2">
                  <el-image
                    :src="spot.image"
                    class="w-full h-28 object-cover group-hover:scale-105 transition-transform duration-300"
                  >
                    <template #error>
                      <div class="w-full h-28 flex items-center justify-center bg-gray-200 dark:bg-gray-600">
                        <el-icon :size="24" class="text-gray-400 dark:text-gray-500"><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div
                    class="absolute inset-0 bg-black/30 group-hover:bg-black/10 transition-colors"
                  ></div>
                </div>
                <h4
                  class="text-sm font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 line-clamp-1"
                >
                  {{ spot.name }}
                </h4>
                <div
                  class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Ticket /></el-icon>
                    ¥{{ spot.price }}起
                  </span>
                  <el-rate
                    v-model="spot.rating"
                    disabled
                    :max="5"
                    class="scale-75"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 推荐攻略 -->
          <div
            class="recommended-guides bg-white dark:bg-gray-800 rounded-lg shadow-sm p-5 mb-5"
            v-if="guideDetail.recommendedGuides && guideDetail.recommendedGuides.length"
          >
            <h3
              class="text-base font-medium text-gray-900 dark:text-white mb-4"
            >
              推荐攻略
            </h3>
            <div class="space-y-4">
              <div
                v-for="guide in guideDetail.recommendedGuides"
                :key="guide.id"
                class="guide-item group cursor-pointer"
                @click="$router.push('/guides/' + guide.id)"
              >
                <div class="relative rounded-lg overflow-hidden mb-2">
                  <el-image
                    :src="guide.cover"
                    class="w-full h-28 object-cover group-hover:scale-105 transition-transform duration-300"
                  >
                    <template #error>
                      <div class="w-full h-28 flex items-center justify-center bg-gray-200 dark:bg-gray-600">
                        <el-icon :size="24" class="text-gray-400 dark:text-gray-500"><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <div
                    class="absolute inset-0 bg-black/30 group-hover:bg-black/10 transition-colors"
                  ></div>
                </div>
                <h4
                  class="text-sm font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 line-clamp-2"
                >
                  {{ guide.title }}
                </h4>
                <div
                  class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><View /></el-icon>
                    {{ formatNumber(guide.views) }}
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Star /></el-icon>
                    {{ formatNumber(guide.likes) }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 评论区 -->
          <div
            class="comments-section bg-white dark:bg-gray-800 rounded-lg shadow-sm p-5"
            v-if="guideDetail.comments"
          >
            <h2
              class="text-base font-medium text-gray-900 dark:text-white mb-4"
            >
              评论区
            </h2>
            <!-- 评论输入框 -->
            <div class="mb-4">
              <el-input
                v-model="commentContent"
                type="textarea"
                :rows="2"
                :placeholder="
                  replyTo ? `回复 @${replyTo.name}：` : '分享你的想法...'
                "
                class="text-sm"
              />
              <div class="flex justify-between items-center mt-2">
                <div v-if="replyTo" class="text-xs text-gray-500">
                  回复：<span class="text-primary-600"
                    >@{{ replyTo.name }}</span
                  >
                  <el-button
                    type="text"
                    size="small"
                    class="ml-1 !p-0"
                    @click="cancelReply"
                    >取消回复</el-button
                  >
                </div>
                <div class="flex items-center gap-2">
                  <el-button size="small" @click="resetComment">重置</el-button>
                  <el-button type="primary" size="small" @click="submitComment">
                    {{ replyTo ? "回复" : "发表评论" }}
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 评论列表 -->
            <div class="space-y-4">
              <div
                v-for="comment in guideDetail.comments"
                :key="comment.id"
                class="comment-item"
              >
                <div class="flex items-start">
                  <el-avatar
                    :size="28"
                    :src="comment.user.avatar"
                    class="mr-2"
                  />
                  <div class="flex-1 min-w-0">
                    <div class="flex items-center justify-between mb-1">
                      <div>
                        <span
                          class="font-medium text-gray-900 dark:text-white text-xs mr-2"
                        >
                          {{ comment.user.name }}
                        </span>
                        <span class="text-xs text-gray-500">
                          {{ formatTime(comment.time) }}
                        </span>
                      </div>
                      <el-button
                        text
                        type="primary"
                        size="small"
                        class="text-xs !px-2"
                        @click="handleReply(comment)"
                      >
                        回复
                      </el-button>
                    </div>
                    <p
                      class="text-[8px] text-gray-600 dark:text-gray-400 mb-2 break-all whitespace-pre-wrap leading-relaxed"
                    >
                      {{ comment.content }}
                    </p>
                    <!-- 回复列表 -->
                    <div
                      v-if="comment.replies && comment.replies.length"
                      class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-2 space-y-2"
                    >
                      <div
                        v-for="reply in comment.replies"
                        :key="reply.id"
                        class="flex items-start"
                      >
                        <el-avatar
                          :size="24"
                          :src="reply.user.avatar"
                          class="mr-2"
                        />
                        <div class="flex-1 min-w-0">
                          <div class="flex items-center mb-1">
                            <span
                              class="font-medium text-gray-900 dark:text-white text-xs mr-1"
                            >
                              {{ reply.user.name }}
                            </span>
                            <span class="text-xs text-gray-500 mr-1">回复</span>
                            <span
                              class="font-medium text-gray-900 dark:text-white text-xs mr-1"
                            >
                              @{{ comment.user.name }}
                            </span>
                            <span class="text-xs text-gray-500 ml-1">
                              {{ formatTime(reply.time) }}
                            </span>
                          </div>
                          <p
                            class="text-[8px] text-gray-600 dark:text-gray-400 break-all whitespace-pre-wrap leading-relaxed"
                          >
                            {{ reply.content }}
                          </p>
                        </div>
                        <el-button
                          text
                          type="primary"
                          size="small"
                          class="text-xs !px-2"
                          @click="handleReply(reply, comment)"
                        >
                          回复
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载更多 -->
            <div v-if="hasMoreComments" class="flex justify-center mt-4">
              <el-button text size="small" @click="loadMoreComments">
                加载更多评论
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <el-dialog
      v-model="showShareDialog"
      title="分享攻略"
      width="360px"
      align-center
    >
      <div class="share-options grid grid-cols-4 gap-4">
        <div
          v-for="platform in sharePlatforms"
          :key="platform.name"
          class="share-item flex flex-col items-center cursor-pointer hover:text-primary-600 transition-colors"
          @click="handleShareTo(platform)"
        >
          <el-icon :size="24" class="mb-2">
            <component :is="platform.icon" />
          </el-icon>
          <span class="text-sm">{{ platform.label }}</span>
        </div>
      </div>
      <div class="mt-6">
        <div class="flex items-center bg-gray-50 dark:bg-gray-700 rounded p-2">
          <input
            type="text"
            :value="generateShareUrl"
            class="flex-1 bg-transparent border-none outline-none text-sm"
            readonly
          />
          <el-button type="primary" link @click="copyShareUrl">
            复制链接
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Share,
  Star,
  View,
  Timer,
  InfoFilled,
  Van,
  Location,
  Wallet,
  Ticket,
  CopyDocument,
  Wechat,
  Weibo,
  ChatDotRound,
  Picture,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import axios from "@/api/axios";
// 导入模拟数据
import { getGuideDetail } from "@/mock/guideDetailData";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const showShareDialog = ref(false);
const commentContent = ref("");
const hasMoreComments = ref(true);

// 攻略详情数据
const guideDetail = ref({});

// 分享平台
const sharePlatforms = [
  { name: "weixin", icon: "Wechat", label: "微信" },
  { name: "weibo", icon: "Weibo", label: "微博" },
  { name: "qq", icon: "ChatDotRound", label: "QQ" },
  { name: "copy", icon: "CopyDocument", label: "复制链接" },
];

// 生成分享链接
const generateShareUrl = computed(() => {
  return `${window.location.origin}/guides/${guideDetail.value.id}`;
});

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 景点列表数据
const allSpots = ref([]);

// 获取所有景点列表
const fetchAllSpots = async () => {
  try {
    // 构建参数 - 获取所有景点
    const params = {
      pageSize: 100 // 设置足够大的值确保获取所有景点
    };

    const response = await axios.get('/public/spot/list', { params });
    console.log("景点列表API响应:", response);
    
    let spotsData = [];
    
    // 处理不同的响应格式
    if (response.data && response.data.content && Array.isArray(response.data.content)) {
      spotsData = response.data.content;
    } 
    else if (response.data && response.data.code === 200 && response.data.data && response.data.data.content && Array.isArray(response.data.data.content)) {
      spotsData = response.data.data.content;
    }
    else if (response.data && response.data.data && response.data.data.records && Array.isArray(response.data.data.records)) {
      spotsData = response.data.data.records;
    }
    else if (response.data && response.data.data && Array.isArray(response.data.data)) {
      spotsData = response.data.data;
    }
    else if (response.data && Array.isArray(response.data)) {
      spotsData = response.data;
    }
    
    if (spotsData.length > 0) {
      console.log("成功获取到景点数据:", spotsData.length, "条");
      allSpots.value = spotsData;
      return true;
    } else {
      console.warn("API返回的景点数据为空");
      return false;
    }
  } catch (error) {
    console.error("获取景点列表失败:", error);
    return false;
  }
};

// 更新相关景点数据
const updateRelatedSpots = () => {
  if (allSpots.value.length === 0 || !guideDetail.value.title) {
    return;
  }
  
  // 根据攻略标题和描述找出可能相关的景点
  const keywords = [
    ...guideDetail.value.title.split(/\s+/),
    ...guideDetail.value.description.split(/[,，。.、\s]/),
  ];
  
  // 过滤有效关键词
  const validKeywords = keywords.filter(k => k.length >= 2);
  console.log("提取的关键词:", validKeywords);
  
  // 计算每个景点的相关度分数
  const scoredSpots = allSpots.value.map(spot => {
    let score = 0;
    const spotText = `${spot.name || ''} ${spot.description || ''} ${spot.category || ''}`;
    
    validKeywords.forEach(keyword => {
      if (spotText.includes(keyword)) {
        score += 1;
      }
    });
    
    // 如果攻略中已经包含该景点(通过itinerary中的spots)，提高相关度
    if (guideDetail.value.itinerary) {
      guideDetail.value.itinerary.forEach(day => {
        if (day.spots) {
          day.spots.forEach(daySpot => {
            if (daySpot.name === spot.name) {
              score += 5;
            }
          });
        }
      });
    }
    
    return { ...spot, score };
  });
  
  // 按相关度排序并获取前3个
  const relatedSpotsData = scoredSpots
    .filter(spot => spot.score > 0)  // 只选择有相关度的景点
    .sort((a, b) => b.score - a.score)
    .slice(0, 3);
  
  // 如果找到的相关景点不足3个，从所有景点中随机选择补足
  if (relatedSpotsData.length < 3) {
    const remainingSpots = scoredSpots
      .filter(spot => !relatedSpotsData.some(s => s.id === spot.id))
      .sort(() => Math.random() - 0.5)
      .slice(0, 3 - relatedSpotsData.length);
    
    relatedSpotsData.push(...remainingSpots);
  }
  
  // 格式化数据以符合需要的结构
  guideDetail.value.relatedSpots = relatedSpotsData.map(spot => ({
    id: spot.id,
    name: spot.name,
    image: spot.coverImage || spot.cover || "https://img0.baidu.com/it/u=1995709151,1000347016&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
    price: spot.price || 0,
    rating: spot.rating || 4.5
  }));
  
  console.log("更新后的相关景点:", guideDetail.value.relatedSpots);
};

// 从API获取攻略详情
const loadGuideDetailFromApi = async (id) => {
  try {
    const response = await axios.get(`/public/guides/${id}`);
    if (response.data && response.data.code === 200) {
      guideDetail.value = response.data.data;
      return true;
    }
    return false;
  } catch (error) {
    console.error("从API加载攻略详情失败:", error);
    return false;
  }
};

// 从模拟数据加载攻略详情
const loadGuideDetailFromMock = (id) => {
  guideDetail.value = getGuideDetail(id);
};

// 加载攻略详情
const loadGuideDetail = async () => {
  const id = route.params.id;
  if (!id) {
    ElMessage.error("未找到攻略ID");
    router.push("/guides");
    return;
  }

  loading.value = true;
  try {
    // 并行请求：同时获取攻略详情和所有景点
    const [guideSuccess, spotsSuccess] = await Promise.all([
      loadGuideDetailFromApi(id),
      fetchAllSpots()
    ]);
    
    if (!guideSuccess) {
      loadGuideDetailFromMock(id);
    }
    
    // 根据获取的景点数据更新相关景点
    updateRelatedSpots();
  } catch (error) {
    console.error("加载攻略详情失败:", error);
    loadGuideDetailFromMock(id);
  } finally {
    loading.value = false;
  }
};

// 初始化加载
onMounted(() => {
  loadGuideDetail();
});

// 监听guideDetail变化，当数据加载完成时更新相关景点
watch(() => guideDetail.value.title, () => {
  if (guideDetail.value.title && allSpots.value.length > 0) {
    updateRelatedSpots();
  }
});

// 处理收藏
const handleFavorite = async () => {
  try {
    // 如果用户未登录，提示登录
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录");
      return;
    }

    // 尝试调用收藏API
    try {
      await axios.post(`/user/guides/favorite/${guideDetail.value.id}`, {
        isFavorite: !guideDetail.value.isFavorited
      });
    } catch (error) {
      console.error("API调用失败，使用本地状态更新:", error);
    }
    
    // 更新本地状态
    guideDetail.value.isFavorited = !guideDetail.value.isFavorited;
    ElMessage.success(
      guideDetail.value.isFavorited ? "收藏成功" : "已取消收藏",
    );
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 处理分享到具体平台
const handleShareTo = (platform) => {
  // TODO: 实现具体分享逻辑
  ElMessage.success(`分享到${platform.label}`);
  showShareDialog.value = false;
};

// 复制分享链接
const copyShareUrl = async () => {
  try {
    await navigator.clipboard.writeText(generateShareUrl.value);
    ElMessage.success("链接已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 回复相关
const replyTo = ref(null);
const parentComment = ref(null);

// 处理回复
const handleReply = (comment, parent = null) => {
  replyTo.value = comment;
  parentComment.value = parent || comment;
  commentContent.value = "";
};

// 取消回复
const cancelReply = () => {
  replyTo.value = null;
  parentComment.value = null;
  commentContent.value = "";
};

// 重置评论
const resetComment = () => {
  commentContent.value = "";
  replyTo.value = null;
  parentComment.value = null;
};

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  try {
    // 检查用户是否登录
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录");
      return;
    }

    // 构建评论数据
    const commentData = {
      content: commentContent.value,
      replyTo: replyTo.value?.id,
      parentId: parentComment.value?.id,
    };

    // 尝试调用评论API
    try {
      await axios.post(`/user/guides/${guideDetail.value.id}/comment`, commentData);
    } catch (error) {
      console.error("API调用失败，使用本地更新:", error);
    }

    // 模拟添加评论
    if (replyTo.value) {
      const reply = {
        id: Date.now(),
        user: {
          name: "当前用户",
          avatar: "/images/avatars/current-user.jpg",
        },
        content: commentContent.value,
        time: new Date().toISOString(),
      };

      if (!parentComment.value.replies) {
        parentComment.value.replies = [];
      }
      parentComment.value.replies.push(reply);
    } else {
      const newComment = {
        id: Date.now(),
        user: {
          name: "当前用户",
          avatar: "/images/avatars/current-user.jpg",
        },
        content: commentContent.value,
        time: new Date().toISOString(),
        replies: [],
      };
      guideDetail.value.comments.unshift(newComment);
    }

    ElMessage.success(replyTo.value ? "回复成功" : "评论发表成功");
    resetComment();
  } catch (error) {
    console.error("评论发表失败:", error);
    ElMessage.error("评论发表失败");
  }
};

// 加载更多评论
const loadMoreComments = async () => {
  try {
    // 尝试调用加载更多评论API
    try {
      const lastCommentId = guideDetail.value.comments[guideDetail.value.comments.length - 1]?.id;
      const response = await axios.get(`/public/guides/${guideDetail.value.id}/comments`, {
        params: { lastId: lastCommentId }
      });
      
      if (response.data && response.data.code === 200) {
        const newComments = response.data.data;
        if (newComments && newComments.length > 0) {
          guideDetail.value.comments.push(...newComments);
        } else {
          hasMoreComments.value = false;
        }
      } else {
        hasMoreComments.value = false;
      }
    } catch (error) {
      console.error("API调用失败，停止加载更多:", error);
      hasMoreComments.value = false;
    }
  } catch (error) {
    console.error("加载更多评论失败:", error);
    ElMessage.error("加载更多评论失败");
    hasMoreComments.value = false;
  }
};
</script>

<style lang="scss" scoped>
.guide-detail-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .timeline-content {
    .spot-item {
      @apply transition-all duration-300;

      &:hover {
        @apply transform -translate-y-1 shadow-md;
      }
    }
  }

  .food-card {
    @apply transition-all duration-300;

    &:hover {
      @apply transform -translate-y-1 shadow-md;
    }
  }

  .note-card {
    @apply transition-all duration-300;

    &:hover {
      @apply transform -translate-y-1 shadow-md;
    }
  }
}
</style>
